package com.liangxy.news.ui.main.home;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.liangxy.news.R;
import com.liangxy.news.model.News;
import com.liangxy.news.repository.NewsRepository;
import com.liangxy.news.ui.detail.NewsDetailActivity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Adapter for news list
 */
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
    
    private static final String TAG = "NewsAdapter";
    
    private List<News> newsList;
    private NewsRepository newsRepository;
    private String currentUserId;
    
    /**
     * Constructor
     * @param newsList List of news items
     */
    public NewsAdapter(List<News> newsList) {
        this.newsList = newsList;
    }
    
    /**
     * Set news repository and current user ID
     * @param newsRepository News repository
     * @param currentUserId Current user ID
     */
    public void setNewsRepository(NewsRepository newsRepository, String currentUserId) {
        this.newsRepository = newsRepository;
        this.currentUserId = currentUserId;
    }
    
    @NonNull
    @Override
    public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
        return new NewsViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) {
        News news = newsList.get(position);
        holder.bind(news, newsRepository, currentUserId);
    }
    
    @Override
    public int getItemCount() {
        return newsList.size();
    }
    
    /**
     * Update news list data
     * @param newsList New list of news items
     */
    public void updateData(List<News> newsList) {
        this.newsList = newsList;
        notifyDataSetChanged();
    }
    
    static class NewsViewHolder extends RecyclerView.ViewHolder {
        
        private final ImageView ivThumbnail;
        private final TextView tvTitle;
        private final TextView tvSource;
        private final TextView tvDate;
        private final TextView tvCategory;
        private final ImageButton btnFollow;
        
        public NewsViewHolder(@NonNull View itemView) {
            super(itemView);
            
            ivThumbnail = itemView.findViewById(R.id.ivThumbnail);
            tvTitle = itemView.findViewById(R.id.tvTitle);
            tvSource = itemView.findViewById(R.id.tvSource);
            tvDate = itemView.findViewById(R.id.tvDate);
            tvCategory = itemView.findViewById(R.id.tvCategory);
            btnFollow = itemView.findViewById(R.id.btnFollow);
        }
        
        /**
         * Bind news data to view
         * @param news News data
         * @param newsRepository News repository
         * @param currentUserId Current user ID
         */
        public void bind(News news, NewsRepository newsRepository, String currentUserId) {
            if (news == null) {
                Log.e(TAG, "Cannot bind null news");
                return;
            }
            
            // 设置标题
            tvTitle.setText(news.getTitle());
            
            // 设置来源
            String source = news.getSource();
            if (TextUtils.isEmpty(source)) {
                source = news.getAuthor_name();
            }
            if (TextUtils.isEmpty(source)) {
                tvSource.setVisibility(View.GONE);
            } else {
                tvSource.setVisibility(View.VISIBLE);
                tvSource.setText(source);
            }
            
            // 格式化并设置日期
            String dateStr = news.getDate();
            if (TextUtils.isEmpty(dateStr)) {
                tvDate.setVisibility(View.GONE);
            } else {
                try {
                    SimpleDateFormat inputFormat;
                    // 判断日期格式是否包含时间
                    if (dateStr.contains(":")) {
                        inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                    } else {
                        inputFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                    }
                    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                    Date date = inputFormat.parse(dateStr);
                    tvDate.setText(outputFormat.format(date));
                    tvDate.setVisibility(View.VISIBLE);
                } catch (ParseException e) {
                    Log.e(TAG, "Error formatting date: " + dateStr, e);
                    tvDate.setText(dateStr);
                    tvDate.setVisibility(View.VISIBLE);
                }
            }
            
            // 设置分类
            String category = news.getCategory();
            if (TextUtils.isEmpty(category)) {
                tvCategory.setVisibility(View.GONE);
            } else {
                tvCategory.setVisibility(View.VISIBLE);
                tvCategory.setText(category);
            }
            
            // 设置缩略图
            String thumbnail = news.getThumbnail_pic_s();
            
            if (thumbnail != null) {
                try {
                    Glide.with(itemView.getContext())
                            .load(thumbnail)
                            .placeholder(R.drawable.placeholder_image)
                            .error(R.drawable.placeholder_image)
                            .centerCrop()
                            .into(ivThumbnail);
                } catch (Exception e) {
                    Log.e(TAG, "Error loading thumbnail: " + e.getMessage());
                    ivThumbnail.setImageResource(R.drawable.placeholder_image);
                }
            } else {
                ivThumbnail.setImageResource(R.drawable.placeholder_image);
            }
            
            // 设置关注按钮状态
            updateFollowButtonState(news, newsRepository, currentUserId);
            
            // 设置点击监听器
            itemView.setOnClickListener(v -> {
                try {
                    if (news.getUniquekey() == null || news.getUniquekey().isEmpty()) {
                        Log.e(TAG, "Cannot open news detail: news ID is null or empty");
                        Toast.makeText(itemView.getContext(), R.string.error_news_not_found, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    Intent intent = new Intent(itemView.getContext(), NewsDetailActivity.class);
                    intent.putExtra(NewsDetailActivity.EXTRA_NEWS_ID, news.getUniquekey());
                    itemView.getContext().startActivity(intent);
                } catch (Exception e) {
                    Log.e(TAG, "Error opening news detail: " + e.getMessage());
                    Toast.makeText(itemView.getContext(), R.string.error_opening_news, Toast.LENGTH_SHORT).show();
                }
            });
        }
        
        /**
         * 更新关注按钮状态
         * @param news 新闻
         * @param newsRepository 新闻仓库
         * @param currentUserId 当前用户ID
         */
        private void updateFollowButtonState(final News news, final NewsRepository newsRepository, final String currentUserId) {
            if (newsRepository == null) {
                btnFollow.setVisibility(View.GONE);
                return;
            }
            
            btnFollow.setVisibility(View.VISIBLE);
            
            // 检查是否已关注
            if (currentUserId != null && !currentUserId.isEmpty()) {
                // 如果有用户ID，使用异步方法检查该用户是否关注了这条新闻
                newsRepository.isFollowingAsync(currentUserId, news.getUniquekey(), isFollowed -> {
                    // 在主线程上更新UI
                    if (itemView.getContext() != null && itemView.getContext() instanceof Activity) {
                        ((Activity) itemView.getContext()).runOnUiThread(() -> {
                            // 设置按钮图标
                            btnFollow.setImageResource(isFollowed ? 
                                    R.drawable.ic_favorite_filled : R.drawable.ic_favorite_border);
                            
                            // 设置按钮点击监听器
                            setupFollowButtonClickListener(news, newsRepository, currentUserId, isFollowed);
                        });
                    }
                });
            } else {
                // 如果没有用户ID，直接使用新闻对象的关注状态
                boolean isFollowed = news.isFollowed();
                btnFollow.setImageResource(isFollowed ? 
                        R.drawable.ic_favorite_filled : R.drawable.ic_favorite_border);
                
                // 设置按钮点击监听器
                setupFollowButtonClickListener(news, newsRepository, currentUserId, isFollowed);
            }
        }
        
        /**
         * 设置关注按钮点击监听器
         */
        private void setupFollowButtonClickListener(final News news, final NewsRepository newsRepository, 
                                                  final String currentUserId, final boolean isFollowed) {
            btnFollow.setOnClickListener(v -> {
                if (currentUserId == null || currentUserId.isEmpty()) {
                    // 未登录
                    Toast.makeText(itemView.getContext(), 
                            R.string.login_to_follow, Toast.LENGTH_SHORT).show();
                    return;
                }
                
                if (isFollowed) {
                    // 取消关注
                    newsRepository.unfollowNews(currentUserId, news.getUniquekey());
                    btnFollow.setImageResource(R.drawable.ic_favorite_border);
                    Toast.makeText(itemView.getContext(), 
                            R.string.unfollow_success, Toast.LENGTH_SHORT).show();
                } else {
                    // 关注
                    newsRepository.followNews(currentUserId, news.getUniquekey());
                    btnFollow.setImageResource(R.drawable.ic_favorite_filled);
                    Toast.makeText(itemView.getContext(), 
                            R.string.follow_success, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
} 